# -*- coding=utf-8
import smtplib
import email.mime.text
# 负责构造文本
from email.mime.text import MIMEText
# 负责构造图片
from email.mime.image import MIMEImage
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from email.header import Header
from MailConfig import SendFrom
from MailConfig import SendTo
from MailConfig import PassWord
from MailConfig import MailSubject
from MailConfig import MailContent

class SendMail:
    def __init__(self):
        self.smtp_server = 'smtp.qq.com'

    def InitMailContent(self):
        mailMsg = MIMEMultipart('related')
        mailMsg['From'] = SendFrom
        mailMsg['To'] = SendTo
        mailMsg['Subject'] = Header(MailSubject)
        content = MIMEText(MailContent, 'plain', 'utf-8')
        mailMsg.attach(content)
        self.sendMail(mailMsg)

    def sendMail(self, mailMsg):
        try:
            # smtp协议的默认端口是25，QQ邮箱smtp服务器端口是465,第一个参数是smtp服务器地址，第二个参数是端口，第三个参数是超时设置,这里必须使用ssl证书，要不链接不上服务器
            server = smtplib.SMTP_SSL(self.smtp_server, 465, timeout = 2)
            # 打印出与服务器的交互信息
            server.set_debuglevel(1)
            # 登录邮箱
            server.login(SendFrom, PassWord)
            #发送邮件，第一个参数是发送方地址，第二个参数是接收方列表，列表中可以有多个接收方地址，表示发送给多个邮箱，msg.as_string()将MIMEText对象转化成文本
            server.sendmail(SendFrom, SendTo.split(','), mailMsg.as_string())
            server.quit()
            print('success')
        except smtplib.SMTPException as e:
            print("Error: unable to send email")
